package com.woniuxy.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.utils.Result;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class RoleUrlFilter extends OncePerRequestFilter {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String nowPath = request.getRequestURI();
        System.out.println(nowPath);


        List<String> urls = (List<String>) request.getSession().getAttribute("urls");

        boolean bool=false;
        if(urls!=null){
            for (String url : urls) {
                if (antPathMatcher.match(url,nowPath)) {
                    bool=true;
                    break;
                }

            }
        }

        if(bool||antPathMatcher.match("/swagger-ui.html",nowPath)||antPathMatcher.match("/webjars/**",nowPath)||antPathMatcher.match("/swagger-resources",nowPath)||antPathMatcher.match("/swagger-resources/**",nowPath)||antPathMatcher.match("/v2/api-docs",nowPath)||antPathMatcher.match("/swagger-resources/**",nowPath)){
            filterChain.doFilter(request,response);
        }else {
            Result result= Result.success(403,"没有权限",null);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().write(json);
            response.getWriter().flush();

        }




    }
}
